#-*- coding:utf-8 -*-
#  This is NOT a freeware, use is subject to license terms
#  @author: hzq <151680523@qq.com>

# @version     $Id:filename.php  http://www.cnblogs.com/huangcong/archive/2011/09/18/2180711.html
from __future__ import division

import time

import chardet
import urllib
import urllib2
__author__ = "Administrator"
__date__ = "$2011-10-25 16:11:32$"
__all__ = [
    "hostParser",
    "strDiff",
    "debug", 'replairUrl', 'safeDecode', 'quote_buffer'
]

def hostParser(url):
    r = {}
    if url.find('//') > -1:
        r['type'] = url[0:7]

    r['host'] = url[7:url[7:].find('/') + 7]
    r['superhost'] = r['host'][r['host'].find('.') + 1:]

    return r


def strDiff(s1, s2):

    if len(s2) > len(s1):
        s1, s2 = (s2, s1)

    same = 0
    diff = 0
    len1 = len(s1)
    len2 = len1

    for i in s1:
        t = s2.find(i)

        if t > -1:
            s2 = s2[t:]
            same = same + len1
        else:
            diff = diff + len2
            len1 = len1-1
    s = same / (diff + same)


    return [same, diff, s]

def replairUrl(host, url):
    if  url.find('http://') < 0:
        if host['host'][0] == '/':
            host['host'] = host['host'][1:]
        s = 'http://%s/%s' % (host['host'], url)
        #debug(s)


        return s
    else:
        return url


def debug(s):
    print '==========This is debug message begin==============\n'
    print s
    print '==========This is debug message end ==============\n'
    time.sleep(6)



def safeDecode(strs, charset='utf-8'):
    if strs:
        strs = strs.strip()
       
        c = chardet.detect(strs)['encoding']
        if c == 'GB2312':
            c = 'gbk'
         
        t = unicode(strs, c)
          
        return  t.encode(charset, 'ignore')
    else:
        return ''
   
    
    


def quote_buffer(buf):
    """
    chinese to mysql
    """
    retstr = ''.join(map(lambda c:'%02x' % ord(c), buf))
    retstr = "x'" + retstr + "'"
    return retstr
    
  



def doPost(url, data):
    data = urllib.urlencode(data)
    request = urllib2.Request(url, data)
    response = urllib2.urlopen(request)
    file = response.read()
    if response.code != 200:
        return 'error code:' + response.code
    else:
        return file

 

    
    



